#include<iostream>
#include<vector>
using namespace std;
class Solution {
    int ret = 0;
    int target = 0;
    int count;
    int row, col;
    bool check[21][21] = { false };
public:
    int uniquePathsIII(vector<vector<int>>& nums) {
        row = nums.size();
        col = nums[0].size();
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (nums[i][j] == 0) target++;
            }
        }
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (nums[i][j] == 1) {
                    check[i][j] = true;
                    dfs(nums, i, j);
                    check[i][j] = false;
                }
            }
        }
        return ret;
    }
    void dfs(vector<vector<int>>& nums, int i, int j) {
        if (nums[i][j] == 2) {
            if (count == target)ret++;
            return;
        }
        int dx[4] = { 0,0,1,-1 };
        int dy[4] = { 1,-1,0,0 };
        for (int k = 0; k < 4; k++) {
            int x = i + dx[k], y = j + dy[k];
            if (x >= 0 && y >= 0 && x <= row - 1 && y <= col - 1 && check[x][y] == false && nums[x][y] >= 0) {
                if (nums[x][y] == 0) {
                    check[x][y] = true;
                    count++;
                    dfs(nums, x, y);
                    check[x][y] = false;
                    count--;
                }
                else {
                    dfs(nums, x, y);
                }
            }
        }
        return;
    }
};